

TodosCtrl.$inject = ['$scope', 
                     '$location', 
                     '$rootScope',
                     '$dialog',
                     'LoginValidate', 
                     'ItemsGetAllByCat', 
                     'LoginService', 
                     'mySharedService',
                     'GetUsersByProjects',
                     'TodoUpdateItem',
                     'TodoDeleteItem',
                     'TodoRemoveCategory',
                     'TodoGetAll'];



function TodosCtrl($scope, 
                   $location,
                   $rootScope,
                   $dialog,
                   LoginValidate, 
                   ItemsGetAllByCat,
                   LoginService, 
                   sharedService,
                   GetUsersByProjects,
                   TodoUpdateItem, 
                   TodoDeleteItem,
                   TodoRemoveCategory,
                   TodoGetAll) {


 /* $scope.editMode = true*/
    
  console.log ("TodosCtrl", LoginService.logged)
   
    // If not logged
    if (!LoginService.logged)
    {
      $location.url ("/login")
      return;
      /*LoginValidate.get(function(data) {
        console.log ("data, ", data)
      })*/
    }

    $scope.sortableOptions = {
      update: function(e, ui) { 

        $scope.$digest();
        console.log ("TODO AGGIORNATO:>", $scope.todos)
      },
      
    };


    /*LoginValidate.get(function(data) {
      console.log ("LoginValidate", data)
    })*/
    
    $scope.$on('handleBroadcast', function() {
        console.log ("LOGGED")
      });  


    /*ItemsGetAllByCat.get({catId: 2}, function(data) {
            
             console.log ("data", data)
        $scope.phones = data.result;
        $scope.orderItemProp = 'label';
    });*/

    /*GetUsersByProjects.get(function(data) {
        
        $scope.users = data.result;
    })
*/

  
  
  $scope.todosCategories = [];

  $scope.init = function () {

    $scope.refreshAllTodos();

  }

  $scope.refreshAllTodos = function () {


    /*TodoGetAll.get(  { }, 
      function(data) {
        //$scope.todos = data.result             
        console.log (":::>", data.result)
      }
    );*/

    TodoGetAll.get({ }, function(data) {
      $scope.todos = data.todos  
      $scope.priorities = data.priorities;
      $scope.populate ()   
      console.log ("11data", data)

    });

  }




  $scope.populate = function () {
    var cats =[];
    //cats.push ({catId: -1, catLabel: ""})
    cats.push ({label: "All categories", value: ""})

    for (var i = 0; i < $scope.todos.length; i++) {
      //cats.push ($scope.todos[i])
      cats.push ({label: $scope.todos[i].catLabel, 
                  value: $scope.todos[i].catLabel})
    };

    $scope.todosCategories = cats;
    console.log ("::>", $scope.todosCategories )

    $scope.filterCategorySelected = cats[0]
  }




   $scope.updateTodo = function (todo, todoIndex, catIndex, altro) {
    console.log ("UPDATE:", todo, todoIndex, catIndex, altro)
      
      // No Title specified
      if (todo.title == "") {
          
        // Remove eement from TODO OPENED
        $scope.todos[catIndex].opened.splice(todoIndex, 1)

      } 

      console.log ("::::>", todo.pippo)
      // Update the TODO
      TodoUpdateItem.get(
        {
          id: todo.id,
          ownerId: todo.ownerId,
          priority: todo.priority,
          title: todo.title,
        }, 
        function(data) {

          // If ERRORS refresh all
          if (data.result.status == "error")
          {
             $scope.init ();
          }
          
            //$scope.todos[catIndex].opened[todoIndex].title = "CIAI"
            /*$scope.$digest();*/
              /* todo.title= todo.title   */  
        }
      );

    // SERVER: UPDATE or ADD THE NEW TODO VALUE
//        todo.id = "ciuao" 
    //$scope.todos[catIndex].opened[todoIndex].id = "NEW ID FROM SERVER SIDE"
    console.log ($scope.todos[catIndex].opened)


     /* todo.id = "ciuao" 
        $scope.todos[catIndex].opened[todoIndex].id = "NEW ID FROM SERVER SIDE"
*/

   }

   // Invoked when user presses the Cancel Button when editing Todo
   $scope.cancelTodo = function (todo, todoIndex, catIndex) {

      // If a Cancel is done with a new TODO (that has no ID) remove the provvisory element
      if (todo.id == "" ) {
        // Remove eement from TODO OPENED
       $scope.todos[catIndex].opened.splice(todoIndex, 1)
      }
   }


   // Remove todo
    $scope.removeTodo = function (todo, todoIndex, catIndex) {

      console.log ("TodoDeleteItem", todo)
      TodoDeleteItem.get(
          {
            catId: todo.id,
          }, 
            function(data) {
              // in any case refresh all

             if (data.result.status == "ok")
             {
              //$scope.refreshAllTodos();
              $scope.todos[catIndex].opened.splice(todoIndex, 1)
             }
            }
          );

   }

   

   $scope.changeTodoStatus = function (todo, todoIndex, catIndex) {
    //console.log ("changeTodoStatus", todoIndex, catIndex, todo)
      
     // Add element to completed
     $scope.todos[catIndex].completed.splice(0, 0, todo);

     // Remove element from TODO OPENED
     $scope.todos[catIndex].opened.splice(todoIndex, 1)

     console.log ("::>", $scope.todos[catIndex].completed,  $scope.todos[catIndex].completed.length)

   }

   $scope.changeTodoCompletedStatus = function (todo, todoIndex, catIndex) {
    //console.log ("changeTodoStatus", todoIndex, catIndex, todo)
      
     // Add element to completed
     $scope.todos[catIndex].opened.splice(0, 0, todo);

     // Remove element from TODO OPENED
     $scope.todos[catIndex].completed.splice(todoIndex, 1)

     console.log ("::>", $scope.todos[catIndex].completed,  $scope.todos[catIndex].completed.length)

   }


   $scope.addTodo = function (cat, index) {

    $scope.filterCategorySelected = "";
    $scope.filterOwnerSelected = "";
    $scope.filterProprity = "";

    console.log ("$rootScope.config.id,", $rootScope.config)
   /* console.log ("cat: ", cat.id, index)*/
     //$scope.todos.push({id: "", name: "Use double-click to edit this comment"});

    var newTodo = {};
    newTodo.id = "";
    newTodo.title = ""
    newTodo.priority = 0
    newTodo.attach = false
    newTodo.commented = false
    newTodo.comments = 0
    newTodo.ownerId = $rootScope.config.user.id,
    newTodo.ownerName = $rootScope.config.user.displayedName;

    

      $scope.todos[index].opened.splice(0, 0, newTodo);

     /*$scope.todos[index].opened.push({id: "", 
                                      title: "", 
                                      priority: 0, 
                                      attach: false,
                                      commented: false,
                                      comments: 0,
                                      ownerId: $rootScope.config.user.id,
                                      ownerName: $rootScope.config.user.displayedName});
*/

   }


  


  $scope.addCatDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: true,
    templateUrl: "todoAddCategory.html",
    /*template:  t,*/ // OR: templateUrl: 'path/to/view.html',
    controller: 'TodoListHelpDialogCtrl'
  };


  // ADD CATEGORY
  $scope.addTodoCategoryDialog = function(){
    var d = $dialog.dialog($scope.addCatDialogOpts);
    d.open().then(function(result){

      if(result)
      {
        // ADD CATEGORY ACTION
        if (result.action == "add")
        {
          console.log (":>",result.msg, result.action)
          var newTodoCat = {};
          newTodoCat.catLabel = result.msg
          newTodoCat.catId = "2121"
          newTodoCat.opened = []
          newTodoCat.completed = []
          

          $scope.todos.splice(0, 0, newTodoCat);
        }
    /*    alert('dialog closed with result: ' + result);*/
      }
    });
  };

  
  // REMOVE CATEGORY
  $scope.removeCategory = function (cat, index) {


/*
    console.log ("remove cat", cat, index)*/
    var title = 'Remove this Category';
    var msg = 'Are you sure you want to remove this category and all its todo?';
    var btns = [{result:'cancel', label: 'Cancel'}, {result:'ok', label: 'OK', cssClass: 'btn-primary'}];

    $dialog.messageBox(title, msg, btns)
      .open()
      .then(function(result){
      /*  alert('dialog closed with result: ' + result);
*/
        if (result == "ok") {
          TodoRemoveCategory.get(
          {
            catId: cat.catId,            
          }, 
            function(data) {
              // in any case refresh all
              //$scope.refreshAllTodos();

              if (data.result.status == "ok")
              {
                console.log ("index!!", index)
                  $scope.todos.splice(index, 1)
              }
            }
          );


        }
    });
  };



  $scope.todoListHelpOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: true,
    templateUrl: "todoListHelp.html",
    /*template:  t,*/ // OR: templateUrl: 'path/to/view.html',
  };



  $scope.openHelp = function(){
    var d = $dialog.dialog($scope.todoListHelpOpts);
    d.open().then(function(result){

      if(result)
      {
        // ADD CATEGORY ACTION
        if (result.action == "add")
        {
          console.log (":>",result.msg, result.action)
          var newTodoCat = {};
          newTodoCat.catLabel = result.msg
          newTodoCat.catId = "2121"
          newTodoCat.opened = []
          newTodoCat.completed = []
          

          $scope.todos.splice(0, 0, newTodoCat);
        }
    /*    alert('dialog closed with result: ' + result);*/
      }
    });
  };


}








// the dialog is injected in the specified controller
function TodoListHelpDialogCtrl($scope, dialog, TodoAddNewCategory){

  $scope.close = function(result){

    var obj  = {}

    // Save the category name if exists
    if (result != undefined) 
      obj.msg = result;

    // MSG IS REQUIRED
    if (obj.msg == undefined || obj.msg == "")
      return;

    obj.action = "add"  
      dialog.close(obj);

    TodoAddNewCategory.get(
    {
      label: obj.msg,
    }, 
      function(data) {

        // If ERRORS refresh all
        if (data.result.status == "ok")
        {

           $scope.closeDialog(obj)
            
        }
        
          //$scope.todos[catIndex].opened[todoIndex].title = "CIAI"
          /*$scope.$digest();*/
            /* todo.title= todo.title   */  
      }
    );


    $scope.closeDialog = function (obj) {
       console.log ("SSS",dialog, obj)
       dialog.close(obj);
    }


  };




  $scope.addNewCategory = function () {

    

    
  }



  $scope.clear = function(result){

    if (result == undefined) var result  = {}
    result.action = "clear"
    dialog.close(result);
  };
}


TodoListHelpDialogCtrl.$inject = ['$scope', 
                     'dialog',
                     'TodoAddNewCategory'];
